<script>
import { useBaseStore, useWorktoolStore } from '@/stores'
import { modalShow } from '@/utils/utils'
export default {
  onLaunch: async function () {
    uni.$myNotifyEventName = 'notify'
    const baseStore = useBaseStore()
    //返回仓库现有的服务器地址
    let baseUrl = baseStore.record
    const opts = {
      title: '服务器IP地址确认',
      editable: true,
      confirmText: '确定',
      cancelText: '取消',
      content: baseUrl,
    }
    function ab2hex(buffer) {
      var hexArr = Array.prototype.map.call(new Uint8Array(buffer), function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      })
      // console.log('ab2hex: ', hexArr)
      return hexArr
    }
    // CRC-16/MODBUS 校验
    function crc16modbus(data) {
      const dataBytes = data.map((v) => parseInt(v, 16))
      let crc = 0xffff
      const polynomial = 0xa001 // This is the polynomial x^16 + x^15 + x^2 + 1

      for (const byte of dataBytes) {
        crc ^= byte
        for (let i = 0; i < 8; i++) {
          if (crc & 0x0001) {
            crc = ((crc >> 1) ^ polynomial) & 0xffff
          } else {
            crc >>= 1
          }
        }
      }
      return crc.toString(16).toUpperCase().padStart(4, '0').match(/\w{2}/g).reverse()
    }
    //#ifndef H5
    try {
      const res = await modalShow(opts)
      // console.log(res)
      //将设置返回的新的服务器，存储到仓库（为空时，就存储原来的服务器地址）
      if (res) {
        baseStore.setRecord(res)
      } else {
        baseStore.setRecord(baseUrl)
      }
    } catch (err) {
      console.log('用户取消')
    }
    const deviceStore = useWorktoolStore()
    //在这里监听蓝牙数据，只执行一次，避免重复产生蓝牙监听
    uni.onBLECharacteristicValueChange((res) => {
      // console.log('listenNotify Change：', res)
      const optsNotify = deviceStore.opts.notify
      const localName = deviceStore.opts.localName
      // console.log('localName', localName)
      // console.log('optsNotify', optsNotify)
      //如果换蓝牙设备，则不执行uni.$emit,编码搞串了
      if (!optsNotify) return
      if (
        optsNotify.deviceId === res.deviceId &&
        optsNotify.serviceId === res.serviceId &&
        optsNotify.characteristicId === res.characteristicId
      ) {
        // 将监听到的数据转换成16进制字符串数组及校验。后续操作统一以此数据
        // buffer转16进制字符串数组
        const resData = ab2hex(res.value)
        // console.log('listenNotify resData', resData)
        // 校验数据(仅针对非GL-BLE设备)
        if (!localName.startsWith('GL-BLE')) {
          const crc = crc16modbus(resData.slice(0, -2)).join('').toUpperCase()
          // console.log('crc', crc)
          const crcRes = resData.slice(-2).join('').toUpperCase()
          // console.log('crcRes', crcRes)
          if (crcRes !== crc) {
            throw new Error('crc校验失败，数据错误')
          }
        }
        uni.$emit(uni.$myNotifyEventName, resData)
      }
    })
    // 监听附近蓝牙连接变化
    uni.onBLEConnectionStateChange(function (res) {
      const currDeviceId = deviceStore.deviceId.currDeviceId
      console.log('App-currDeviceId', currDeviceId)
      //监听附近设备为当前使用设备并且是否连接状态，不是连接状态，将currDeviceId清空
      if (res.deviceId !== currDeviceId || !res.connected) {
        deviceStore.deviceId.currDeviceId = ''
      }
      console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
    })
    //#endif
  },
  onShow: function () {
    // console.log('App Show')
  },
  onHide: function () {
    // console.log('App Hide')
  },
  //设置全局变量
  globalData: {
    isFromLogin: false,
    hasNetwork: true,
    protosUtils: {},
  },
}
</script>

<style lang="scss">
// @import '@/common/style/common-style.scss';
// @import '@/common/style/base-style.scss';
</style>
